package com.bicycle.wxpublic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bicycle.common.entity.base.Message;
import com.bicycle.common.enums.HasViolationEnum;
import com.bicycle.common.enums.ReportResourceEnum;
import com.bicycle.common.enums.ReportStatusEnum;
import com.bicycle.common.enums.SequenceBusinessCodeEnum;
import com.bicycle.service.entity.BicycleCommonFile;
import com.bicycle.service.entity.BicycleSequenceReportDetail;
import com.bicycle.service.entity.BicycleSequenceReportPhoto;
import com.bicycle.service.entity.BicycleSequenceReportProcess;
import com.bicycle.service.mapper.BicycleCommonFileMapper;
import com.bicycle.service.mapper.BicycleSequenceReportDetailMapper;
import com.bicycle.service.mapper.BicycleSequenceReportPhotoMapper;
import com.bicycle.service.mapper.BicycleSequenceReportProcessMapper;
import com.bicycle.wxpublic.handle.DownloadPictureThread;
import com.bicycle.wxpublic.service.ReportProcessService;
import com.bicycle.wxpublic.service.WeChatService;
import com.bicycle.wxpublic.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author : layne
 * @Date: 2020/8/8
 * @Time: 9:21
 * Description:
 */
@Service
public class ReportProcessServiceImpl implements ReportProcessService {

    @Autowired
    private BicycleSequenceReportDetailMapper reportDetailMapper;
    @Autowired
    private BicycleSequenceReportProcessMapper reportProcessMapper;
    @Autowired
    private BicycleSequenceReportPhotoMapper reportPhotoMapper;
    @Autowired
    private BicycleCommonFileMapper fileMapper;

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private Environment environment;


    @Override
    public Message queryReportDetailList(ReportProcessListDto reportProcessListDto) {
        Message message = new Message();
        QueryWrapper<BicycleSequenceReportDetail> queryWrapper = new QueryWrapper<BicycleSequenceReportDetail>();
        BicycleSequenceReportDetail bicycleSequenceReportDetail = new BicycleSequenceReportDetail();
        bicycleSequenceReportDetail.setEnterpriseNo(reportProcessListDto.getEnterpriseNo());
        bicycleSequenceReportDetail.setDistrictId(reportProcessListDto.getDistrictId());
        bicycleSequenceReportDetail.setReportResource(reportProcessListDto.getReportResource());
        queryWrapper.setEntity(bicycleSequenceReportDetail);
        if (reportProcessListDto.getReportStatus() == 0) {
            queryWrapper.in("report_status", 0, 1);
        } else if (reportProcessListDto.getReportStatus() == 2) {
            queryWrapper.eq("report_status", 2);
        } else if (reportProcessListDto.getReportStatus() == 3) {
            queryWrapper.eq("report_status", 3);
        }
        queryWrapper.orderByDesc("order_type", "report_time");

        List<BicycleSequenceReportDetail> reportdetailList = reportDetailMapper.selectList(queryWrapper);
        // 未处理的count(包含未处理和已退回),已处理的count,已结案的count,政府巡查count,群众举报count,平台监测count
        long notReplyCount, replyCount, endCount, govCount, massCount, platformCount = 0;

        QueryWrapper<BicycleSequenceReportDetail> countWrapper = new QueryWrapper<BicycleSequenceReportDetail>();
        bicycleSequenceReportDetail.setReportResource(null);
        countWrapper.setEntity(bicycleSequenceReportDetail);
        countWrapper.in("report_status", 0, 1);

        // 未处理
        notReplyCount = reportDetailMapper.selectCount(countWrapper);

        // 已处理
        bicycleSequenceReportDetail.setReportStatus(ReportStatusEnum.REPORT_STATUS_2.getKey());
        replyCount = reportDetailMapper.selectCount(new QueryWrapper<BicycleSequenceReportDetail>(bicycleSequenceReportDetail));

        // 已结案
        bicycleSequenceReportDetail.setReportStatus(ReportStatusEnum.REPORT_STATUS_3.getKey());
        endCount = reportDetailMapper.selectCount(new QueryWrapper<BicycleSequenceReportDetail>(bicycleSequenceReportDetail));

        if (reportProcessListDto.getReportStatus() == 0) {
            // 是待处理的时候，report_status包含(0,1)
//            countWrapper.in("report_status", 0, 1);
            bicycleSequenceReportDetail.setReportResource(ReportResourceEnum.GOV.getKey());
            govCount = reportDetailMapper.selectCount(countWrapper);
            bicycleSequenceReportDetail.setReportResource(ReportResourceEnum.MASS.getKey());
            massCount = reportDetailMapper.selectCount(countWrapper);
            bicycleSequenceReportDetail.setReportResource(ReportResourceEnum.PLATFORM.getKey());
            platformCount = reportDetailMapper.selectCount(countWrapper);

        } else {

            bicycleSequenceReportDetail.setReportStatus(reportProcessListDto.getReportStatus());
            bicycleSequenceReportDetail.setReportResource(ReportResourceEnum.GOV.getKey());
            govCount = reportDetailMapper.selectCount(new QueryWrapper<BicycleSequenceReportDetail>(bicycleSequenceReportDetail));
            bicycleSequenceReportDetail.setReportResource(ReportResourceEnum.MASS.getKey());
            massCount = reportDetailMapper.selectCount(new QueryWrapper<BicycleSequenceReportDetail>(bicycleSequenceReportDetail));
            bicycleSequenceReportDetail.setReportResource(ReportResourceEnum.PLATFORM.getKey());
            platformCount = reportDetailMapper.selectCount(new QueryWrapper<BicycleSequenceReportDetail>(bicycleSequenceReportDetail));
            ;
        }

        List<ReportProcessListVo.ReportPRocessDetailListVo> respList = new ArrayList<ReportProcessListVo.ReportPRocessDetailListVo>();
        for (BicycleSequenceReportDetail detail : reportdetailList) {
            ReportProcessListVo.ReportPRocessDetailListVo reportDetailResp = new ReportProcessListVo.ReportPRocessDetailListVo();
            BeanUtil.copyProperties(detail, reportDetailResp, new String[]{"reportType"});
            if (StringUtils.isBlank(detail.getReportType())) {
                reportDetailResp.setReportType(new String[]{});
            } else {
                reportDetailResp.setReportType(detail.getReportType().split(","));
            }
            respList.add(reportDetailResp);
        }

        ReportProcessListVo reportProcessListVo = new ReportProcessListVo();
        reportProcessListVo.setEndCount(endCount);
        reportProcessListVo.setNotReplyCount(notReplyCount);
        reportProcessListVo.setReplyCount(replyCount);
        reportProcessListVo.setGovCount(govCount);
        reportProcessListVo.setMassCount(massCount);
        reportProcessListVo.setPlatformCount(platformCount);
        reportProcessListVo.setReportdetailList(respList);
        Map<String, Object> resultMap = new HashMap<String, Object>();

        message.setResult(reportProcessListVo);
        return message;
    }

    @Override
    public Message queryWxReportDetail(Integer detailId) {
        Message message = new Message();
        // 获取举报详情
        BicycleSequenceReportDetail reportDetail = reportDetailMapper.selectById(detailId);

        // 获取处理记录
        QueryWrapper<BicycleSequenceReportProcess> processQueryWrapper = new QueryWrapper<BicycleSequenceReportProcess>();
        BicycleSequenceReportProcess qDetailProcessRecord = new BicycleSequenceReportProcess();
        qDetailProcessRecord.setDetailId(detailId);
        processQueryWrapper.setEntity(qDetailProcessRecord);
        processQueryWrapper.orderByAsc("create_time");
        List<BicycleSequenceReportProcess> processRecordList = reportProcessMapper.selectList(processQueryWrapper);

        // 获取举报图片
        QueryWrapper<BicycleSequenceReportPhoto> photoQueryWrapper = new QueryWrapper<BicycleSequenceReportPhoto>();
        photoQueryWrapper.setEntity(BicycleSequenceReportPhoto.builder().detailId(detailId).photoType(1).build());
        List<BicycleSequenceReportPhoto> detailPhotoList = reportPhotoMapper.selectList(photoQueryWrapper);

        // 设置请求url
        detailPhotoList.forEach(detailPhoto -> {
            if (detailPhoto.getFileId() != null) {
                BicycleCommonFile commonFile = fileMapper.selectById(detailPhoto.getFileId());
                detailPhoto.setPhotoUrl(commonFile.getDownloadPath() + commonFile.getRelativePath());
            }
        });
        // 处理记录
        List<ReportProcessDetailVo.ReportProcessDetailRecordVo> detailProcessRecordList = new ArrayList<ReportProcessDetailVo.ReportProcessDetailRecordVo>();
        for (BicycleSequenceReportProcess record : processRecordList) {
            ReportProcessDetailVo.ReportProcessDetailRecordVo processRecord = new ReportProcessDetailVo.ReportProcessDetailRecordVo();
            // 操作类型等于处理的 才有处理前图片和处理后图片
            if (record.getOperateType().intValue() == 1) {

                // 处理前
                List<BicycleSequenceReportPhoto> preDetailPhotoList = reportPhotoMapper.selectList(new QueryWrapper<BicycleSequenceReportPhoto>(BicycleSequenceReportPhoto.builder().processId(record.getId()).photoType(2).build()));
                // 处理后
                List<BicycleSequenceReportPhoto> afterDetailPhotoList = reportPhotoMapper.selectList(new QueryWrapper<BicycleSequenceReportPhoto>(BicycleSequenceReportPhoto.builder().processId(record.getId()).photoType(3).build()));
                preDetailPhotoList.forEach(preDetailPhoto -> {
                    if (preDetailPhoto.getFileId() != null) {
                        BicycleCommonFile commonFile = fileMapper.selectById(preDetailPhoto.getFileId());
                        preDetailPhoto.setPhotoUrl(commonFile.getDownloadPath() + commonFile.getRelativePath());
                    }
                });
                afterDetailPhotoList.forEach(afterDetailPhoto -> {
                    if (afterDetailPhoto.getFileId() != null) {
                        BicycleCommonFile commonFile = fileMapper.selectById(afterDetailPhoto.getFileId());
                        afterDetailPhoto.setPhotoUrl(commonFile.getDownloadPath() + commonFile.getRelativePath());
                    }
                });
                processRecord.setPreDetailPhotoList(preDetailPhotoList);
                processRecord.setAfterDetailPhotoList(afterDetailPhotoList);
            }
            // 拷贝属性
            BeanUtil.copyProperties(record, processRecord);
            detailProcessRecordList.add(processRecord);
        }
        //东门街道不需要 违规车辆数据
        ReportProcessListVo.ReportPRocessDetailListVo reportDetailResp = new ReportProcessListVo.ReportPRocessDetailListVo();
        BeanUtil.copyProperties(reportDetail, reportDetailResp, new String[]{"reportType"});
        if (StringUtils.isBlank(reportDetail.getReportType())) {
            reportDetailResp.setReportType(new String[]{});
        } else {
            reportDetailResp.setReportType(reportDetail.getReportType().split(","));
        }
        ReportProcessDetailVo reportProcessDetailVo = new ReportProcessDetailVo();
        // 详情图片
        reportProcessDetailVo.setDetailPhotoList(detailPhotoList);
        // 处理记录
        reportProcessDetailVo.setProcessList(detailProcessRecordList);
        // 举报详情
        reportProcessDetailVo.setReportDetailList(reportDetailResp);
        message.setResult(reportProcessDetailVo);
        return message;
    }

    @Override
    public Message updateReportDetail(ReportProcessDto reportProcessDto) {
        Message message = new Message();
        BicycleSequenceReportDetail detail = reportDetailMapper.selectById(reportProcessDto.getDetailId());
        if (detail == null) {
            message.setCode(SequenceBusinessCodeEnum.CODE_INFO_NOT_EXIST.getKey());
            message.setMessage(SequenceBusinessCodeEnum.CODE_INFO_NOT_EXIST.getValue());
            return message;
        }
        // 案件已处理
        if (detail.getReportStatus() == ReportStatusEnum.REPORT_STATUS_2.getKey().intValue()) {
            message.setCode(SequenceBusinessCodeEnum.CODE_CASE_PROCESSED.getKey());
            message.setMessage(SequenceBusinessCodeEnum.CODE_CASE_PROCESSED.getValue());
            return message;
        }
        Date overTime = detail.getProcessTime() == null ? detail.getReportTime() : detail.getProcessTime();
        detail.setHasTrue(reportProcessDto.getHasTrue());
        detail.setRemark(reportProcessDto.getRemark());
        detail.setProcessUserId(reportProcessDto.getProcessUserId());
        detail.setProcessUserName(reportProcessDto.getProcessUserName());
        detail.setProcessTime(new Date());
        detail.setReportStatus(ReportStatusEnum.REPORT_STATUS_2.getKey()); // 已处理
        if (reportProcessDto.getHasTrue() != null && reportProcessDto.getHasTrue().intValue() == 2) { // 重复案件
            detail.setRepeatCaseNo(reportProcessDto.getRepeatCaseNo()); // 重复案件编号
        }
        if (detail.getHasOvertime() == null) {
            if (detail.getProcessTime().after(DateUtil.offsetHour(overTime, detail.getOrderType() == 2 ? 1 : 2))) {
                // 已超时
                detail.setHasOvertime(1);
            } else {
                detail.setHasOvertime(0);
            }
        }
        reportDetailMapper.updateById(detail);

        int detailId = detail.getDetailId();
        BicycleSequenceReportProcess detailProcessRecord = new BicycleSequenceReportProcess();
        detailProcessRecord.setDetailId(detailId);
        detailProcessRecord.setMobile(reportProcessDto.getMobile());
        detailProcessRecord.setHasTrue(reportProcessDto.getHasTrue());
        detailProcessRecord.setRemark(reportProcessDto.getRemark());
        detailProcessRecord.setProcessUserId(reportProcessDto.getProcessUserId());
        detailProcessRecord.setProcessUserName(reportProcessDto.getProcessUserName());
        detailProcessRecord.setProcessTime(new Date());
        // 已处理
        detailProcessRecord.setOperateType(1);
        detailProcessRecord.setProcessEnterpriseNo(reportProcessDto.getEnterpriseNo());
        detailProcessRecord.setProcessEnterpriseName(reportProcessDto.getEnterpriseName());
        detailProcessRecord.setCreateTime(new Date());

        // 获取本次的处理记录
        reportProcessMapper.insert(detailProcessRecord);
        int processId = detailProcessRecord.getId();
        if (reportProcessDto.getHasTrue() != null && reportProcessDto.getHasTrue().intValue() == 2) {
            // 重复案件
            ReportRepeatCaseDto caseDto = new ReportRepeatCaseDto();
            caseDto.setRepeatCaseNo(reportProcessDto.getRepeatCaseNo());
            caseDto.setDistrictId(reportProcessDto.getDistrictId());
            caseDto.setEnterpriseNo(reportProcessDto.getEnterpriseNo());
            Message ret = this.queryRepeatCase(caseDto);
            if (ret.getCode() != 0) {
                return ret;
            }
            ReportProcessDetailVo.ReportProcessDetailRecordVo respProcessRecord = (ReportProcessDetailVo.ReportProcessDetailRecordVo) ret.getResult();
            for (BicycleSequenceReportPhoto prePhoto : respProcessRecord.getPreDetailPhotoList()) {
                // 设置处理前的图片
                BicycleSequenceReportPhoto tempPhoto = new BicycleSequenceReportPhoto();
                tempPhoto.setPhotoType(prePhoto.getPhotoType());
                tempPhoto.setDetailId(detail.getDetailId());
                tempPhoto.setFileId(prePhoto.getFileId());
                tempPhoto.setMediaId(prePhoto.getMediaId());
                tempPhoto.setCreateTime(new Date());
                tempPhoto.setProcessId(processId);
                reportPhotoMapper.insert(tempPhoto);
            }
            for (BicycleSequenceReportPhoto afterPhoto : respProcessRecord.getAfterDetailPhotoList()) {
                // 设置处理后的图片
                BicycleSequenceReportPhoto tempPhoto = new BicycleSequenceReportPhoto();
                tempPhoto.setPhotoType(afterPhoto.getPhotoType());
                tempPhoto.setDetailId(detail.getDetailId());
                tempPhoto.setFileId(afterPhoto.getFileId());
                tempPhoto.setMediaId(afterPhoto.getMediaId());
                tempPhoto.setCreateTime(new Date());
                tempPhoto.setProcessId(processId);
                reportPhotoMapper.insert(tempPhoto);
            }
        } else {
            new DownloadPictureThread(reportProcessDto.getPreMediaId(), reportProcessDto.getAfterMediaId(), null, reportPhotoMapper, detailId, processId,
                    fileMapper, weChatService, environment.getProperty("file.upload.path"), environment.getProperty("file.download.path"), environment).start();
        }
        return message;
    }

    @Override
    public Message queryRepeatCase(ReportRepeatCaseDto reportRepeatCaseDto) {
        Message message = new Message();
        BicycleSequenceReportDetail repeatDetail = reportDetailMapper.selectOne(new QueryWrapper<BicycleSequenceReportDetail>(BicycleSequenceReportDetail.builder().reportNo(reportRepeatCaseDto.getRepeatCaseNo())
                .enterpriseNo(reportRepeatCaseDto.getEnterpriseNo()).districtId(reportRepeatCaseDto.getDistrictId()).build()));
        if (repeatDetail == null) {
            message.setCode(SequenceBusinessCodeEnum.CODE_INFO_NOT_EXIST.getKey());
            message.setMessage(SequenceBusinessCodeEnum.CODE_INFO_NOT_EXIST.getValue());
            return message;
        }
        if (repeatDetail != null && repeatDetail.getReportStatus() != ReportStatusEnum.REPORT_STATUS_3.getKey().intValue()) {
            message.setCode(SequenceBusinessCodeEnum.CODE_CASE_NOT_CLOSE.getKey());
            message.setMessage(SequenceBusinessCodeEnum.CODE_CASE_NOT_CLOSE.getValue());
            return message;
        }
        // 查询企业处理记录
        BicycleSequenceReportProcess processRecord = reportProcessMapper.selectOne(new QueryWrapper<BicycleSequenceReportProcess>(BicycleSequenceReportProcess.builder().detailId(repeatDetail.getDetailId()).operateType(1).build()));
        ReportProcessDetailVo.ReportProcessDetailRecordVo respProcessRecord = new ReportProcessDetailVo.ReportProcessDetailRecordVo();
        if (processRecord != null) {
            // 处理前
            List<BicycleSequenceReportPhoto> preDetailPhotoList =
                    reportPhotoMapper.selectList(new QueryWrapper<BicycleSequenceReportPhoto>(BicycleSequenceReportPhoto.builder().processId(processRecord.getId()).photoType(2).build()));
            // 处理后
            List<BicycleSequenceReportPhoto> afterDetailPhotoList =
                    reportPhotoMapper.selectList(new QueryWrapper<BicycleSequenceReportPhoto>(BicycleSequenceReportPhoto.builder().processId(processRecord.getId()).photoType(3).build()));

            preDetailPhotoList.forEach(detailPhoto -> {
                if (detailPhoto.getFileId() != null) {
                    BicycleCommonFile commonFile = fileMapper.selectById(detailPhoto.getFileId());
                    detailPhoto.setPhotoUrl(commonFile.getDownloadPath() + commonFile.getRelativePath());
                }
            });
            afterDetailPhotoList.forEach(detailPhoto -> {
                if (detailPhoto.getFileId() != null) {
                    BicycleCommonFile commonFile = fileMapper.selectById(detailPhoto.getFileId());
                    detailPhoto.setPhotoUrl(commonFile.getDownloadPath() + commonFile.getRelativePath());
                }
            });
            respProcessRecord.setPreDetailPhotoList(preDetailPhotoList);
            respProcessRecord.setAfterDetailPhotoList(afterDetailPhotoList);
        }
        // 拷贝属性
        BeanUtil.copyProperties(processRecord, respProcessRecord);
        message.setResult(respProcessRecord);
        return message;
    }
}
